package tk.mybatis.springboot.wexin.util;

import java.net.URI;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import net.sf.json.JSONObject;

public class ECXBUtils {
	private static Logger log = LogManager.getLogger(ECXBUtils.class);
	public static JSONObject callApi(Object obj, String url){
		JSONObject json = null;
		try (CloseableHttpClient httpClient = HttpClients.createDefault();) {
			String reqJson = JSONObject.fromObject(obj).toString();
			HttpPost postRequest = new HttpPost(url);
			StringEntity input = new StringEntity(reqJson, "UTF-8");
			log.info("reqJson:" + reqJson);
			input.setContentType("application/json");
			postRequest.setEntity(input);

			HttpResponse response = httpClient.execute(postRequest);
			int rtnCode = response.getStatusLine().getStatusCode();
			log.info("rtnCode:" + rtnCode);

			if (rtnCode == 200) {
				String resJson = EntityUtils.toString(response.getEntity(), "UTF-8");
				log.info("resJson:" + resJson);
				json = JSONObject.fromObject(resJson);
				return json;
			}

		} catch (Exception ex) {
			log.error("error:" + ex);
		}

		return json;
	}
	
	public static JSONObject callApi2(String obj, String url){
		JSONObject json = null;
		try (CloseableHttpClient httpClient = HttpClients.createDefault();) {
			HttpPost postRequest = new HttpPost(url);
			StringEntity input = new StringEntity(obj, "UTF-8");
			log.info("reqJson:" + obj);
			input.setContentType("application/json");
			postRequest.setEntity(input);

			HttpResponse response = httpClient.execute(postRequest);
			int rtnCode = response.getStatusLine().getStatusCode();
			log.info("rtnCode:" + rtnCode);

			if (rtnCode == 200) {
				String resJson = EntityUtils.toString(response.getEntity(), "UTF-8");
				log.info("resJson:" + resJson);
				json = JSONObject.fromObject(resJson);
				return json;
			}

		} catch (Exception ex) {
			log.error("error:" + ex);
		}

		return json;
	}
}
